package com.CmJava.servlet.modelAndView.view;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

public class InternalResourceView implements View {

    private String url;
    private String contentType = "text/html;charset=ISO-8859-1";

    public InternalResourceView(String viewName) {
        url=viewName;
    }

    @Override
    public void render(Object modelInternal, HttpServletRequest request, HttpServletResponse response) {
        this.renderMergedOutputModel(request,response);
    }

    private void renderMergedOutputModel(HttpServletRequest request, HttpServletResponse response) {

        String dispatcherPath = this.prepareForRendering(request, response);
        RequestDispatcher rd = this.getRequestDispatcher(request, dispatcherPath);
        try {
            rd.forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private RequestDispatcher getRequestDispatcher(HttpServletRequest request, String dispatcherPath) {
        return request.getRequestDispatcher(dispatcherPath);
    }

    private String prepareForRendering(HttpServletRequest request, HttpServletResponse response) {
        if (url.equals(request.getRequestURI())){
            throw new RuntimeException("erro loop!");
        }
        return url;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
